from urllib import urlencode, urlopen

from plugins import json
from config import config_obj, logger, plugin_prefix
from helper import level_triggered

'''
Notfier:
    @interface notify
'''


class Requests(object):
    def __init__(self, url, **kwargs):
        self.url = url

    def get(self, query={}):
        if query:
            query = urlencode(query)
            self.url += '?' + query
        f = urlopen(self.url)
        return f.getcode()

    def post(self, data={}):
        f = urlopen(self.url, data)
        return f.getcode()

class BaseNotifier(object):

    def _json2obj(self, json_obj):
        return json.loads(json_obj)

    def topic(self, obj, threshold):
        ''' topic to notify
        '''

    def notify(self):
        '''interface for notifiying'''

class Notifier(BaseNotifier):

    def __init__(self, to='to_print'):
        self.to = to

    def to_print(self):
        pass

    def to_mcs(self):
        pass

    def notify(self, json_obj):
        obj = self._json2obj(json_obj)
        config = config_obj[plugin_prefix + obj[0]]
        logger.debug("%s's config: %s" % (obj[0], config))
        # logger.debug('obj is: %s' % repr(obj))
        getattr(self, obj[0])(obj[1], config)

    def harddisk(self, obj, config):
        def _parse(v):
            d = {}
            for l in v:
                _li = l.split('|')
                d[_li[0]] = [int(i) for i in _li[1:]]
            return d

        check_points = [(k, _parse(v)) for k, v in config.items()]
        for check_point, data in check_points:
            for part, thresholds in data.iteritems():
                logger.debug('%s thresholds: %s' % (part, thresholds))
                for o in obj:
                    if not check_point in o:
                        logger.warn('Could not found check_point: %s in %s' % (check_point, o))
                        break
                    if o['mounted_on'] == part:
                        cap = o[check_point]
                        level = level_triggered(cap, thresholds)
                        getattr(logger, level)('%s capacity was: %s [%s]' % (part,  cap, level))

    def memory(self, obj, config):
        pass

    def logged_user(self, obj, config):
        pass

    def tcp_state(self, obj, config):
        pass

    def fsprocstat(self, obj, config):
        pass

    def socket_state(self, obj, config):
        pass

    def traffic(self, obj, config):
        pass

    def load(self, obj, config):
        pass

    def auth_su(self, obj, config):
        pass

    def auth_ssh(self, obj, config):
        pass


class MCSNotfier(BaseNotifier):

    def notify(self, msg_obj):
        pass


